//
//  Grid.swift
//  Memorize
//
//  Created by yuchuntao on 2020/8/9.
//  Copyright © 2020 yuchuntao. All rights reserved.
//

import SwiftUI

struct Grid<Item,ItemView> : View where Item : Identifiable, ItemView : View {
    var items: [Item]
    var itemForView: (Item) -> ItemView
    
    init(_ items: [Item], itemForView: @escaping (Item) -> ItemView) {
        self.items = items
        self.itemForView = itemForView
    }
    
    func body(for layout: GridLayout) -> some View {
        ForEach(items) { item in
            self.body(for: layout, item: item)
        }
    }
    
    func body(for layout: GridLayout, item: Item) -> some View {
        let index = items.firstIndex(matching: item)
        return self.itemForView(item)
            .frame(width: layout.itemSize.width, height: layout.itemSize.height)
            .position(layout.location(ofItemAt: index!))
    }
    
    var body: some View {
        GeometryReader { geometry in
            self.body(for: GridLayout(itemCount: self.items.count, in: geometry.size))
        }
    }
}

